import React, { useState, useEffect } from 'react';
import { useParams, useNavigate, Link as RouterLink } from 'react-router-dom';
import {
    Box,
    Container,
    Paper,
    Typography,
    Button,
    Grid,
    Divider,
    Breadcrumbs,
    Link,
    Tab,
    Tabs,
    CircularProgress,
    Card,
    CardContent,
    CardMedia,
    CardActions,
    Chip,
    Alert,
    IconButton,
    Menu,
    MenuItem,
    ListItemIcon,
    ListItemText,
    Tooltip
} from '@mui/material';
import {
    ArrowBack as ArrowBackIcon,
    Home as HomeIcon,
    ViewInAr as ModelIcon,
    CloudUpload as UploadIcon,
    CloudDownload as DownloadIcon,
    Edit as EditIcon,
    ImageOutlined as ThumbnailIcon,
    MoreVert as MoreIcon,
    Refresh as RefreshIcon,
    FormatShapes as ObjIcon,
    ThreeDRotation as GlbIcon,
    Code as StlIcon,
    Inventory2 as FbxIcon
} from '@mui/icons-material';
import { motion, AnimatePresence } from 'framer-motion';
import { styled } from '@mui/material/styles';

import { useModelContext } from '../contexts/ModelContext';
import FileUpload from '../components/FileUpload';

// 用于格式图标的映射
const formatIcons = {
    'glb': <GlbIcon />,
    'obj': <ObjIcon />,
    'stl': <StlIcon />,
    'fbx': <FbxIcon />
};

const StyledTab = styled(Tab)(({ theme }) => ({
    textTransform: 'none',
    fontSize: '1rem',
    fontWeight: 500,
    minHeight: 48,
    padding: '0 16px',
    '&.Mui-selected': {
        color: theme.palette.primary.main,
        fontWeight: 600
    }
}));

const ModelFiles = () => {
    const { id } = useParams();
    const navigate = useNavigate();
    const {
        models,
        loading,
        fetchModels,
        uploadModelFile,
        downloadModelFile,
        getModelThumbnail,
        fileLoading,
        fileError,
        uploadProgress,
        setFileLoading,
        setFileError
    } = useModelContext();

    const [currentModel, setCurrentModel] = useState(null);
    const [tabValue, setTabValue] = useState(0);
    const [thumbnail, setThumbnail] = useState(null);
    const [thumbnailLoading, setThumbnailLoading] = useState(false);
    const [formatMenuAnchor, setFormatMenuAnchor] = useState(null);

    // 获取模型信息
    useEffect(() => {
        if (!models.length) {
            fetchModels();
        } else {
            const foundModel = models.find(model => model.id === id);
            setCurrentModel(foundModel || null);
        }
    }, [id, models, fetchModels]);

    // 获取缩略图
    useEffect(() => {
        if (currentModel) {
            const fetchThumbnail = async () => {
                setThumbnailLoading(true);
                try {
                    const thumbnailData = await getModelThumbnail(id);
                    setThumbnail(thumbnailData);
                } catch (error) {
                    console.error('获取缩略图失败:', error);
                } finally {
                    setThumbnailLoading(false);
                }
            };

            fetchThumbnail();
        }
    }, [currentModel, id, getModelThumbnail]);

    // 处理文件上传
    const handleUpload = (file) => {
        uploadModelFile(id, file);
    };

    // 处理文件下载
    const handleDownload = (format = null) => {
        setFormatMenuAnchor(null);

        try {
            if (!currentModel) {
                if (setFileError) {
                    setFileError('无法下载：找不到模型数据');
                }
                return;
            }

            if (setFileLoading) {
                setFileLoading(true);
            }

            // 构建模型数据
            const modelData = {
                name: currentModel.name || '未命名模型',
                description: currentModel.description || '',
                geometry: currentModel.geometry || {}
            };

            // 根据格式导出不同类型文件
            const exportData = async () => {
                try {
                    if (!format || format === 'json') {
                        // 导出JSON格式
                        const jsonString = JSON.stringify(modelData, null, 2);
                        const dataUri = 'data:application/json;charset=utf-8,' + encodeURIComponent(jsonString);
                        const fileName = `${modelData.name || 'model'}.json`;

                        const link = document.createElement('a');
                        link.href = dataUri;
                        link.download = fileName;
                        document.body.appendChild(link);
                        link.click();

                        setTimeout(() => {
                            document.body.removeChild(link);
                        }, 100);
                    } else {
                        // 导入并使用ModelExporter
                        const { exportModel } = await import('../components/exporters/ModelExporter');
                        await exportModel(modelData, format);
                    }

                    if (setFileLoading) {
                        setFileLoading(false);
                    }
                } catch (error) {
                    console.error(`下载${format || 'JSON'}模型失败:`, error);
                    if (setFileError) {
                        setFileError(`下载${format || 'JSON'}模型失败: ${error.message}`);
                    }
                    if (setFileLoading) {
                        setFileLoading(false);
                    }
                }
            };

            exportData();
        } catch (error) {
            console.error('下载模型失败:', error);
            if (setFileError) {
                setFileError('下载模型失败: ' + error.message);
            }
            if (setFileLoading) {
                setFileLoading(false);
            }
        }
    };

    // 处理菜单打开
    const handleOpenFormatMenu = (event) => {
        setFormatMenuAnchor(event.currentTarget);
    };

    // 处理菜单关闭
    const handleCloseFormatMenu = () => {
        setFormatMenuAnchor(null);
    };

    // 处理返回
    const handleGoBack = () => {
        navigate('/models');
    };

    // 渲染页面
    if (!currentModel && loading) {
        return (
            <Box
                sx={{
                    display: 'flex',
                    justifyContent: 'center',
                    alignItems: 'center',
                    minHeight: '80vh'
                }}
            >
                <CircularProgress />
            </Box>
        );
    }

    if (!currentModel && !loading) {
        return (
            <Container maxWidth="lg" sx={{ py: 4 }}>
                <Alert
                    severity="error"
                    sx={{ mb: 3 }}
                    action={
                        <Button color="inherit" size="small" onClick={handleGoBack}>
                            返回模型列表
                        </Button>
                    }
                >
                    找不到ID为 {id} 的模型
                </Alert>
            </Container>
        );
    }

    return (
        <Container maxWidth="lg" sx={{ py: 4 }}>
            {/* 面包屑导航 */}
            <Breadcrumbs sx={{ mb: 2 }}>
                <Link
                    component={RouterLink}
                    to="/"
                    underline="hover"
                    color="inherit"
                    sx={{ display: 'flex', alignItems: 'center' }}
                >
                    <HomeIcon sx={{ mr: 0.5 }} fontSize="inherit" />
                    首页
                </Link>
                <Link
                    component={RouterLink}
                    to="/models"
                    underline="hover"
                    color="inherit"
                    sx={{ display: 'flex', alignItems: 'center' }}
                >
                    <ModelIcon sx={{ mr: 0.5 }} fontSize="inherit" />
                    我的模型
                </Link>
                <Typography color="text.primary" sx={{ display: 'flex', alignItems: 'center' }}>
                    <UploadIcon sx={{ mr: 0.5 }} fontSize="inherit" />
                    模型文件管理
                </Typography>
            </Breadcrumbs>

            {/* 标题区 */}
            <Paper
                component={motion.div}
                initial={{ opacity: 0, y: -20 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ duration: 0.5 }}
                elevation={0}
                sx={{
                    p: 3,
                    backgroundImage: 'linear-gradient(120deg, #e3f2fd 0%, #bbdefb 100%)',
                    borderRadius: 2,
                    mb: 4,
                    display: 'flex',
                    justifyContent: 'space-between',
                    alignItems: 'center'
                }}
            >
                <Box>
                    <Typography variant="h4" component="h1" sx={{ fontWeight: 700 }}>
                        {currentModel.name}
                    </Typography>
                    <Typography variant="body1" color="text.secondary">
                        {currentModel.description || '无描述'}
                    </Typography>
                </Box>
                <Box>
                    <Button
                        variant="outlined"
                        startIcon={<ArrowBackIcon />}
                        onClick={handleGoBack}
                        sx={{ mr: 2 }}
                    >
                        返回列表
                    </Button>
                    <Button
                        variant="outlined"
                        startIcon={<EditIcon />}
                        component={RouterLink}
                        to={`/models/edit/${id}`}
                    >
                        编辑信息
                    </Button>
                </Box>
            </Paper>

            {/* 标签栏 */}
            <Paper sx={{ mb: 4 }}>
                <Tabs
                    value={tabValue}
                    onChange={(e, newValue) => setTabValue(newValue)}
                    variant="fullWidth"
                    textColor="primary"
                    indicatorColor="primary"
                >
                    <StyledTab icon={<UploadIcon />} label="上传文件" />
                    <StyledTab icon={<DownloadIcon />} label="下载管理" />
                    <StyledTab icon={<ThumbnailIcon />} label="缩略图" />
                </Tabs>
            </Paper>

            {/* 标签页内容 */}
            <AnimatePresence mode="wait">
                <motion.div
                    key={tabValue}
                    initial={{ opacity: 0, y: 10 }}
                    animate={{ opacity: 1, y: 0 }}
                    exit={{ opacity: 0, y: -10 }}
                    transition={{ duration: 0.3 }}
                >
                    {/* 上传文件标签页 */}
                    {tabValue === 0 && (
                        <Grid container spacing={4}>
                            <Grid item xs={12} md={7}>
                                <Paper sx={{ p: 3, height: '100%' }}>
                                    <Typography variant="h6" gutterBottom>
                                        上传3D模型文件
                                    </Typography>
                                    <Typography variant="body2" color="text.secondary" paragraph>
                                        支持的文件格式: GLB, OBJ, STL, FBX。文件大小限制: 50MB。
                                    </Typography>
                                    <Divider sx={{ my: 2 }} />
                                    <FileUpload
                                        onUpload={handleUpload}
                                        progress={uploadProgress}
                                        isUploading={fileLoading}
                                        error={fileError}
                                    />
                                </Paper>
                            </Grid>
                            <Grid item xs={12} md={5}>
                                <Paper sx={{ p: 3, height: '100%' }}>
                                    <Typography variant="h6" gutterBottom>
                                        文件格式说明
                                    </Typography>
                                    <Typography variant="body2" paragraph>
                                        不同的文件格式适用于不同的用途，以下是支持格式的简要说明：
                                    </Typography>

                                    <Box sx={{ mb: 2 }}>
                                        <Typography variant="subtitle2" fontWeight="bold" sx={{ display: 'flex', alignItems: 'center' }}>
                                            <GlbIcon sx={{ mr: 1 }} /> GLB
                                        </Typography>
                                        <Typography variant="body2" color="text.secondary">
                                            推荐格式，适用于网页3D显示，包含几何、材质和动画。
                                        </Typography>
                                    </Box>

                                    <Box sx={{ mb: 2 }}>
                                        <Typography variant="subtitle2" fontWeight="bold" sx={{ display: 'flex', alignItems: 'center' }}>
                                            <ObjIcon sx={{ mr: 1 }} /> OBJ
                                        </Typography>
                                        <Typography variant="body2" color="text.secondary">
                                            开放格式，广泛兼容，适合静态模型，不支持动画。
                                        </Typography>
                                    </Box>

                                    <Box sx={{ mb: 2 }}>
                                        <Typography variant="subtitle2" fontWeight="bold" sx={{ display: 'flex', alignItems: 'center' }}>
                                            <StlIcon sx={{ mr: 1 }} /> STL
                                        </Typography>
                                        <Typography variant="body2" color="text.secondary">
                                            3D打印常用格式，只包含几何信息，不含材质和颜色。
                                        </Typography>
                                    </Box>

                                    <Box>
                                        <Typography variant="subtitle2" fontWeight="bold" sx={{ display: 'flex', alignItems: 'center' }}>
                                            <FbxIcon sx={{ mr: 1 }} /> FBX
                                        </Typography>
                                        <Typography variant="body2" color="text.secondary">
                                            专业3D格式，支持丰富的材质、贴图和骨骼动画。
                                        </Typography>
                                    </Box>
                                </Paper>
                            </Grid>
                        </Grid>
                    )}

                    {/* 下载管理标签页 */}
                    {tabValue === 1 && (
                        <Box>
                            <Typography variant="h6" gutterBottom>
                                模型文件下载
                            </Typography>
                            <Typography variant="body2" color="text.secondary" paragraph>
                                您可以下载原始格式或转换为其他支持的格式。
                            </Typography>

                            <Card sx={{ maxWidth: 400, mb: 3 }}>
                                <CardMedia
                                    component="img"
                                    height="200"
                                    image={thumbnail || `https://source.unsplash.com/random/400x200/?3d,model&sig=${id}`}
                                    alt={currentModel.name}
                                    sx={{ backgroundColor: 'grey.200' }}
                                />
                                <CardContent>
                                    <Typography variant="h6" component="div">
                                        {currentModel.name}
                                    </Typography>
                                    <Typography variant="body2" color="text.secondary">
                                        上传时间: {new Date(currentModel.createdAt).toLocaleDateString('zh-CN')}
                                    </Typography>
                                    <Box sx={{ display: 'flex', mt: 1 }}>
                                        <Chip
                                            icon={<GlbIcon />}
                                            label="GLB"
                                            variant="outlined"
                                            size="small"
                                            sx={{ mr: 1 }}
                                        />
                                        <Chip
                                            icon={formatIcons['obj']}
                                            label="OBJ"
                                            variant="outlined"
                                            size="small"
                                            sx={{ mr: 1 }}
                                        />
                                        <Chip
                                            icon={formatIcons['stl']}
                                            label="STL"
                                            variant="outlined"
                                            size="small"
                                        />
                                    </Box>
                                </CardContent>
                                <CardActions>
                                    <Button
                                        startIcon={<DownloadIcon />}
                                        onClick={() => handleDownload('json')}
                                        disabled={fileLoading}
                                    >
                                        下载JSON格式
                                    </Button>
                                    <Button
                                        endIcon={<MoreIcon />}
                                        onClick={handleOpenFormatMenu}
                                        disabled={fileLoading}
                                    >
                                        其他格式
                                    </Button>
                                    <Menu
                                        anchorEl={formatMenuAnchor}
                                        open={Boolean(formatMenuAnchor)}
                                        onClose={handleCloseFormatMenu}
                                    >
                                        <MenuItem onClick={() => handleDownload('json')}>
                                            <ListItemIcon>
                                                <DownloadIcon fontSize="small" />
                                            </ListItemIcon>
                                            <ListItemText>JSON格式</ListItemText>
                                        </MenuItem>
                                        <MenuItem onClick={() => handleDownload('obj')}>
                                            <ListItemIcon>
                                                {formatIcons['obj']}
                                            </ListItemIcon>
                                            <ListItemText>OBJ格式</ListItemText>
                                        </MenuItem>
                                        <MenuItem onClick={() => handleDownload('stl')}>
                                            <ListItemIcon>
                                                {formatIcons['stl']}
                                            </ListItemIcon>
                                            <ListItemText>STL格式</ListItemText>
                                        </MenuItem>
                                        <MenuItem onClick={() => handleDownload('glb')}>
                                            <ListItemIcon>
                                                {formatIcons['glb']}
                                            </ListItemIcon>
                                            <ListItemText>GLB格式</ListItemText>
                                        </MenuItem>
                                    </Menu>
                                </CardActions>
                            </Card>

                            {fileLoading && (
                                <Box sx={{ display: 'flex', alignItems: 'center', mt: 2 }}>
                                    <CircularProgress size={24} sx={{ mr: 2 }} />
                                    <Typography>下载处理中...</Typography>
                                </Box>
                            )}

                            {fileError && (
                                <Alert severity="error" sx={{ mt: 2 }}>
                                    {fileError}
                                </Alert>
                            )}
                        </Box>
                    )}

                    {/* 缩略图标签页 */}
                    {tabValue === 2 && (
                        <Box>
                            <Paper sx={{ p: 3 }}>
                                <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
                                    <Typography variant="h6">
                                        模型缩略图
                                    </Typography>
                                    <Tooltip title="重新生成缩略图">
                                        <IconButton onClick={() => getModelThumbnail(id)}>
                                            <RefreshIcon />
                                        </IconButton>
                                    </Tooltip>
                                </Box>
                                <Typography variant="body2" color="text.secondary" paragraph>
                                    系统自动为模型生成缩略图预览，您可以在此查看。
                                </Typography>

                                <Divider sx={{ my: 2 }} />

                                {thumbnailLoading ? (
                                    <Box
                                        sx={{
                                            height: 300,
                                            display: 'flex',
                                            justifyContent: 'center',
                                            alignItems: 'center',
                                            backgroundColor: 'grey.100',
                                            borderRadius: 1
                                        }}
                                    >
                                        <CircularProgress />
                                    </Box>
                                ) : thumbnail ? (
                                    <Box
                                        component="img"
                                        src={thumbnail}
                                        alt={currentModel.name}
                                        sx={{
                                            width: '100%',
                                            maxHeight: 400,
                                            objectFit: 'contain',
                                            borderRadius: 1,
                                            boxShadow: 1
                                        }}
                                    />
                                ) : (
                                    <Box
                                        sx={{
                                            height: 300,
                                            display: 'flex',
                                            flexDirection: 'column',
                                            justifyContent: 'center',
                                            alignItems: 'center',
                                            backgroundColor: 'grey.100',
                                            borderRadius: 1
                                        }}
                                    >
                                        <ThumbnailIcon sx={{ fontSize: 60, color: 'text.secondary', mb: 2 }} />
                                        <Typography variant="body1" color="text.secondary">
                                            没有可用的缩略图
                                        </Typography>
                                        <Typography variant="body2" color="text.secondary">
                                            请先上传模型文件
                                        </Typography>
                                    </Box>
                                )}
                            </Paper>
                        </Box>
                    )}
                </motion.div>
            </AnimatePresence>
        </Container>
    );
};

export default ModelFiles; 